package com.jykj.modbus.equipment.controller;

import com.jykj.modbus.equipment.controller.guard.EquipmentControllerGuard;
import com.jykj.modbus.equipment.entity.ReturnModBus;
import com.jykj.modbus.equipment.entity.guard.Equipment;
import com.jykj.modbus.equipment.entity.guard.EquipmentMessage;
import com.jykj.modbus.equipment.service.SerialPortManager;
import com.jykj.modbus.equipment.service.Test;
import com.jykj.modbus.exception.SendDataToSerialPortFailure;
import com.jykj.modbus.exception.SerialPortOutputStreamCloseFailure;
import com.jykj.modbus.equipment.entity.HttpResponse;
import com.jykj.modbus.utils.ByteUtils;
import com.jykj.util.config.AppConfig;
import com.jykj.util.log.Log;
import gnu.io.SerialPort;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/equipment/equi")
public class EquipmentController extends EquipmentControllerGuard {

	private final static Log log;
	
	static{
		log = Log.getLog("com.jykj.equipment.controller.equipmentControllerGuard");
	}

	/**
	 * 传感器开启串口发送数据并接收
	 * @param qus 查询类型
	 * @param serialPort 串口号
	 * @param sensorType 设备类型
	 * @return Map<String, Object>
	 */
	private Map<String, Object> openPort(String serialPort,  String qus , String sensorType) {
		Map<String, Object> mapData = new HashMap<>();
		ReturnModBus returnModBus = new ReturnModBus();
		String title = "";
		String data = "";
		try {
			Test test = new Test();
			Equipment equipment = new Equipment();
			//传感器类型
			equipment.setSensorType(sensorType);
			//串口号
			equipment.setSerialPort(serialPort);
			List<Equipment> list = this.service.selectEquipmentList(equipment);
			if (list.size() > 0){
				equipment = list.get(0);
			}else {
				return null;
			}
			//通过设备信息查询指令代码
			EquipmentMessage eqm = new EquipmentMessage();
			//设备类型
			eqm.setSensorType(sensorType);
			//查询类型
			eqm.setMessageType(Integer.parseInt(qus));
			List<EquipmentMessage> messages = this.service.selectEquipmentMessage(eqm);
			if (messages.size()>0){
				eqm = messages.get(0);
				title = eqm.getMessageNode();
			}else {
				title = "类型匹配失败;";
			}
			//开启串口
			returnModBus = test.openSerialPort1(null , sensorType , qus, equipment , eqm.getResultsDigits());
			for (int i = 1 ; i < 6 ; i++){
				//如果查询设备类型为电表传感器,需要先发送查询表号指令获取电表表号
				if (sensorType.equals(AppConfig.getProperty("sensor.electricity"))){
					String dataStr = new String();
					for (int e = 6 ; e>0 ; e--){
						String s1 = equipment.getInstrumentNum().substring(e*2-2, e*2);
						dataStr += s1;
					}
					data= "FEFEFEFE68"+dataStr+eqm.getMessage();
				}else {
					data = eqm.getMessage();
				}
				System.out.println(title+"第"+i+"次发送指令:");
				Thread.sleep(1000);
				//发送指令
				SerialPortManager.sendToPort(returnModBus.getSerialport(), ByteUtils.hexStr2Byte(data));
				for (int e = 0 ; e<10 ; e++){
					if (test.equipmentData.getResultsFrame().length() > 0){
						mapData = test.dataProcessing(sensorType, qus, test.equipmentData.getResultsFrame());
						System.out.println("解析完成的串口数据:");
						System.out.println(mapData);
						//关闭串口
						test.closeSerialPort(null);
						return mapData;
					}
					Thread.sleep(1000);
				}
			}
			//关闭串口
			test.closeSerialPort(null);
		} catch (SendDataToSerialPortFailure e) {
			e.printStackTrace();
		} catch (SerialPortOutputStreamCloseFailure e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return mapData;
	}

	/**
	 * 服务端通过“设备识别码”信息查询功能模块，获取对应设备信息并包装为json信息返回服务端
	 * 调用接口后将该接口能调用的指令报文均调用，包装完成后返回服务端
	 * @param eqcode 设备码
	 * @return
	 */
	@ResponseBody
	@GetMapping(value = "/equipmentMessage")
	public HttpResponse equipmentMessage(@Param("eqcode") String eqcode ) {
		EquipmentMessage obj = new EquipmentMessage();
		//通过设备识别码查询
		Equipment equipment = new Equipment();
		equipment.setIdentificationCode(Integer.parseInt(eqcode));
		List<Equipment> equipmentList = this.service.selectEquipmentList(equipment);
		if (equipmentList.size()>0){
			equipment = equipmentList.get(0);
		}
		//通过设备信息查询设备指令
		EquipmentMessage equipmentMessage = new EquipmentMessage();
		equipmentMessage.setSensorType(equipment.getSensorType());
		List<EquipmentMessage> messageList = this.service.selectEquipmentMessage(equipmentMessage);
		List<Map<String, Object>> mapList = new ArrayList<>();
		for (EquipmentMessage equm : messageList){
			Map<String, Object> map = openPort(equipment.getSerialPort(), equm.getMessageType().toString(), equipment.getSensorType());
			mapList.add(map);
		}
		return HttpResponse.success("查询成功!" , mapList);
	}


}	
	
	
